function imageUpload(id,maxsize,callback=false,updata,alowType) {
    var fileDir = "uploads";
    var images = $("#upload_"+id).val();
    $("#upload_"+id+"_text").text("上传中");
    var $file = event.currentTarget;
    var origin_type = $file.files[0].type;
    var file = $file.files;
    if (alowType == "image") {
        if ($.inArray(origin_type,["image/png","image/jpeg"]) < 0) {
            mviewToastr("error","当前只支持上传JPG/PNG图片!");
            $("#upload_"+id).val('');
            $("#upload_"+id+"_text").text("上传");
            return;
        }
    } else {
        if ($.inArray(origin_type,["image/png","image/gif","image/jpeg","image/webp"]) < 0) {
            mviewToastr("error","当前不支持上传此类型图片,请上传JPG/PNG/GIF图片!");
            $("#upload_"+id).val('');
            $("#upload_"+id+"_text").text("上传");
            return;
        }
    }
    // 此3种类型不支持压缩
    if ($.inArray(origin_type,["image/png","image/gif","image/webp"]) >= 0) {
        var formData = new FormData();
        if (file[0].size > maxsize*1000) {
            mviewToastr("error","图片不能大于"+maxsize+"KB,如果是长图请裁剪为多图上传!");
            $("#upload_"+id).val('');
            $("#upload_"+id+"_text").text("上传");
            return;
        }
        aliOssUpload(id,file[0],fileDir,callback,"single",updata);
    } else {
        var reader = new FileReader();
        reader.readAsDataURL(file[0]);
        reader.onload = function (e) {
            var data = e.target.result;
            //加载图片获取图片真实宽度和高度
            var image = new Image();
            image.src = data;
            // 图片先加载完，才可以得到图片宽度和高度
            image.onload = function(){
                var width = image.width;
                var height = image.height;
                if (width > 800) {
                    lrz(file[0],{width: 800,quality:1,fieldName:'images'}).then(function (rst) {
                        var resultSize = (rst.fileLen/1024).toFixed(0);
                        if (resultSize > maxsize) {
                            mviewToastr("error","图片压缩后不能超过"+maxsize+"KB,当前为"+resultSize+"KB。");
                            $("#upload_"+id).val('');
                            $("#upload_"+id+"_text").text("上传");
                            return;
                        }
                        aliOssUpload(id,rst.file,fileDir,callback,"single",updata);
                    }).catch(function (err) {
                        $("#upload_"+id).val('');
                        $("#upload_"+id+"_text").text("上传");
                        mviewToastr("error","图片压缩失败,请上传正确图片或选择其他图片!");
                        return;
                    });
                } else {
                    aliOssUpload(id,file[0],fileDir,callback,"single",updata);
                }
            }
        }
    }
}

function jsUploadMore(id,maxsize,callback=false,updata,alowType) {
    var fileDir = "uploads";
    var images = $("#upload_"+id).val();
    $("#upload_"+id+"_text").text("上传中");
    var $file = event.currentTarget;
    var origin_type = $file.files[0].type;
    var file = $file.files;
    if (alowType == "image") {
        if ($.inArray(origin_type,["image/png","image/jpeg"]) < 0) {
            mviewToastr("error","当前只支持上传JPG/PNG图片!");
            $("#upload_"+id).val('');
            $("#upload_"+id+"_text").text("上传");
            return;
        }
    } else {
        if ($.inArray(origin_type,["image/png","image/gif","image/jpeg","image/webp"]) < 0) {
            mviewToastr("error","当前不支持上传此类型图片,请上传JPG/PNG/GIF图片!");
            $("#upload_"+id).val('');
            $("#upload_"+id+"_text").text("上传");
            return;
        }
    }
    // 此3种类型不支持压缩
    if ($.inArray(origin_type,["image/png","image/gif","image/webp"]) >= 0) {
        var formData = new FormData();
        if (file[0].size > maxsize*1000) {
            mviewToastr("error","图片不能大于"+maxsize+"KB,如果是长图请裁剪为多图上传!");
            $("#upload_"+id).val('');
            $("#upload_"+id+"_text").text("上传");
            return;
        }
        aliOssUpload(id,file[0],fileDir,callback,"list",updata);
    } else {
        var reader = new FileReader();
        reader.readAsDataURL(file[0]);
        reader.onload = function (e) {
            var data = e.target.result;
            //加载图片获取图片真实宽度和高度
            var image = new Image();
            image.src = data;
            // 图片先加载完，才可以得到图片宽度和高度
            image.onload = function(){
                var width = image.width;
                var height = image.height;
                if (width > 800) {
                    lrz(file[0],{width: 800,quality:1,fieldName:'images'}).then(function (rst) {
                        var resultSize = (rst.fileLen/1024).toFixed(0);
                        if (resultSize > maxsize) {
                            mviewToastr("error","图片压缩后不能超过"+maxsize+"KB,当前为"+resultSize+"KB。");
                            $("#upload_"+id).val('');
                            $("#upload_"+id+"_text").text("上传");
                            return;
                        }
                        aliOssUpload(id,rst.file,fileDir,callback,"list",updata);
                    }).catch(function (err) {
                        $("#upload_"+id).val('');
                        $("#upload_"+id+"_text").text("上传");
                        mviewToastr("error","图片压缩失败,请上传正确图片或选择其他图片!");
                        return;
                    });
                } else {
                    aliOssUpload(id,file[0],fileDir,callback,"list",updata);
                }
            }
        }
    }
}

function aliOssUpload(id,file,dir,callback,type,updata){
    var randomId = generateRandomInteger(10000,99999);
    //获取上传的文件名，并得到文件后缀
    if (type == "editor") {
        var point = file.name.lastIndexOf(".");//获取文件后缀
        var file_type = file.name.substr(point);
    } else {
        var fileInput=$("#upload_"+id).val();
        var point = fileInput.lastIndexOf(".");
        var file_type = fileInput.substr(point);//获取文件后缀
    }
    var day = getCurrentTime("day");
    var time = getCurrentTime("time");
    var imageName = randomId+file_type;
    var file_name = dir+"/"+day+"/"+time+randomId+file_type;
    var imageurl = "https://res.yikuaitiao.cn/"+file_name;
    //发送ajax请求我方php后端获取上传OSS时必要的参数信息
    $.ajax({
        type : "get", //提交方式
        url : "/api/upload/upload_access_token",//路径
        data : {
            "dir" : dir
        },//数据，这里使用的是Json格式进行传输
        success : function(res) {//返回数据根据结果进行相应的处理
            res = JSON.parse(res);

            //上返回的参数使用formData中
            let formData = new FormData();
            formData.append('key', file_name);
            formData.append('OSSAccessKeyId', res.accessid);
            formData.append('policy', res.policy);
            formData.append('Signature', res.signature);
            formData.append('callback', res.callback);
            formData.append('success_action_status', 200); // 成功后返回的操作码
            formData.append('file', file);
            //接收到服务端返回的签名参数，开始通过另一个Ajax请求来上传文件到OSS
            //成功获取签名后上传文件到阿里云OSS
            $.ajax({
                type : "POST", //提交方式
                url : res.host,//路径
                dataType:'JSON',
                processData: false,
                cache: false,
                async: false,
                contentType: false,
                data : formData,
                success : function(result) {
                    if (result.Status == "Ok") {
                        if (type == "single") {
                            aliOssUploadBack(id,imageurl,callback,imageName,updata);
                        } else if(type == "editor") {
                            aliOssUploadEditorBack(id,imageurl,callback,imageName,updata);
                        } else {
                            aliOssListsUploadBack(id,imageurl,callback,imageName,updata);
                        }
                    }
                },error:function(err){
                    aliOssListsUploadBack(id,imageurl,callback,imageName,updata);
                    mviewToastr("error","图片上传失败,请联系客服处理！");
                }
            });
        },error:function(err){
            mviewToastr("error","网络异常,请联系客服处理！");
        }
    });
}

function generateRandomInteger(min, max) {
    return Math.floor(Math.random() * (max - min + 1)) + min;
}

function getCurrentTime(type){
    var date = new Date();
    var year = date.getFullYear();
    var month = date.getMonth() + 1;
    var day = date.getDate();
    var hour = date.getHours();
    var minutes = date.getMinutes();
    var seconds = date.getSeconds();
    if (month >= 1 && month <= 9) {
        month = "0" + month;
    }
    if (day >= 0 && day <= 9) {
        day = "0" + day;
    }
    if (hour >= 0 && hour <= 9) {
        hour = "0" + hour;
    }
    if (minutes >= 0 && minutes <= 9) {
        minutes = "0" + minutes;
    }
    if (seconds >= 0 && seconds <= 9) {
        seconds = "0" + seconds;
    }
    if (type == "day") {
        return year+month+day;
    } else {
        return hour+minutes+seconds;
    }
}

function aliOssUploadBack(id,imageurl,callback,imageName,updata) {
    $("#"+id+"_show").attr("src",imageurl).show();
    $("#"+id).val(imageurl);
    // 清空上传选择
    $("#upload_"+id).val('');
    $("#upload_"+id+"_text").text("上传");
    if (callback) {
        jsUploadCallBack(id,imageurl,imageName,updata);
    }
}

function aliOssListsUploadBack(id,imageurl,callback,imageName,updata) {
    var imageid = Math.ceil(Math.random()*10000000);
    $("#"+id+"_lists").prepend('<div id="'+imageid+'"><img src="'+imageurl+'" class="m-file-image"><i class="m-file-del iconfont icon-guanbi" onclick=\'deleteImages("'+id+'","'+imageurl+'","'+imageid+'");\'></i></div>');
    var imageLists = JSON.parse($("#"+id).val());
    imageLists.push(imageurl);
    $("#"+id).val(JSON.stringify(imageLists));
    if (callback) {
        jsUploadCallBack(id,imageurl,imageName,updata);
    }
}

function aliOssUploadEditorBack(id,imageurl,callback,imageName,updata) {
    wangEditorUploadBack(imageurl);
}

function deleteImages(id,image,imageid) {
    $("#"+imageid).remove();
    var images = JSON.parse($("#"+id).val());
    var imageLists = [];
    $.each(images,function(idx,fimage){
        if (fimage != image) {
            imageLists.push(fimage);
        }
    });
    $("#"+id).val(JSON.stringify(imageLists));
    jsImagesListsDeleteCallback();
}

function getScaleSize(that,rst){
    var sourceSize = (that.files[0].size/1024).toFixed(2);
    var resultSize = (rst.fileLen/1024).toFixed(2);
    var scale = parseInt(100 - (resultSize / sourceSize * 100));
    console.log("源文件:"+sourceSize+"KB\r\n压缩后:"+resultSize+"KB\r\n节省:"+scale+"%");
}
